package com.emapp.lccode.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.emapp.lccode.R
import com.emapp.lccode.adapter.GridImageAdapter
import com.emapp.lccode.base.BaseActivity1
import com.emapp.lccode.base.BaseConfig
import com.emapp.lccode.base.EventBusConfig
import com.emapp.lccode.base.EventBusModel
import com.emapp.lccode.bean.CommTypeKt
import com.emapp.lccode.bean.ProblemTypeKt
import com.emapp.lccode.databinding.ActivityOrderAddBinding
import com.emapp.lccode.mode.OrderKtViewModel
import com.emapp.lccode.utils.DividerOrientation
import com.emapp.lccode.utils.GlideEngine
import com.emapp.lccode.utils.ImageFileCompressEngine
import com.emapp.lccode.utils.MapAppUtil
import com.emapp.lccode.utils.MeSandboxFileEngine
import com.emapp.lccode.utils.MmkvUtil
import com.emapp.lccode.utils.MyExternalPreviewEventListener
import com.emapp.lccode.utils.divider
import com.emapp.lccode.utils.getColorExt
import com.emapp.lccode.utils.grid
import com.emapp.lccode.utils.setOnclickNoRepeat
import com.gyf.immersionbar.ktx.immersionBar
import com.hjq.toast.Toaster
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.style.PictureSelectorStyle
import com.luck.picture.lib.utils.MediaUtils
import com.mylhyl.circledialog.CircleDialog
import com.umeng.commonsdk.stateless.UMSLEnvelopeBuild.mContext
import me.hgj.jetpackmvvm.ext.parseState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**
 */
class OrderAddKtActivity : BaseActivity1<OrderKtViewModel, ActivityOrderAddBinding>(),
    AMapLocationListener {

    val form_type: ArrayList<CommTypeKt> = arrayListOf(
        CommTypeKt("0", "内部巡检"),
        CommTypeKt("1", "巡管员"),
        CommTypeKt("2", "投诉报修"),
        CommTypeKt("3", "电话报修")
    )
    var mData: ArrayList<LocalMedia> = arrayListOf()
    var problem_type: ArrayList<ProblemTypeKt> = arrayListOf()
    private val imageAdapter: GridImageAdapter by lazy { GridImageAdapter(this, mData) }
    lateinit var launcherResult: ActivityResultLauncher<Intent>
    private lateinit var locationClient: AMapLocationClient
    private lateinit var locationOption: AMapLocationClientOption
    var imageIds=""
    override fun initView(savedInstanceState: Bundle?) {
        AMapLocationClient.updatePrivacyShow(this, true, true)
        AMapLocationClient.updatePrivacyAgree(this, true)
        immersionBar {
            titleBar(mViewBind.lvTitle.ivBar)
            statusBarDarkFont(true)
            fullScreen(true)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
        }
        launcherResult = createActivityResultLauncher()
        mViewBind.lvTitle.tvTitle.text = "新建工单"
        mViewBind.lvTitle.tvRight.visibility = View.GONE
        EventBus.getDefault().register(this)
        mViewBind.rvList.run {
            grid(4)
            adapter = imageAdapter
            divider {
                orientation = DividerOrientation.HORIZONTAL
                includeVisible = true
                setDivider(10, true)
                setColor(getColorExt(R.color.white))
            }
        }
        imageAdapter.run {
            selectMax = BaseConfig.selectMaxImage
            setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
                override fun onItemClick(v: View?, position: Int) {
                    PictureSelector.create(this@OrderAddKtActivity)
                        .openPreview()
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setSelectorUIStyle(PictureSelectorStyle())
                        .isPreviewFullScreenMode(true)
                        .setExternalPreviewEventListener(MyExternalPreviewEventListener(this@run))
                        .startActivityPreview(position, true, data)
                }

                override fun openPicture() {
                    // 进入相册
                    val selectionModel: PictureSelectionModel =
                        PictureSelector.create(this@OrderAddKtActivity)
                            .openGallery(SelectMimeType.ofImage())
                            .setSelectorUIStyle(PictureSelectorStyle())
                            .setImageEngine(GlideEngine.createGlideEngine()) //.setCropEngine(getCropFileEngine())
                            .setCompressEngine(ImageFileCompressEngine())
                            .setSandboxFileEngine(MeSandboxFileEngine())
                            .setSelectionMode(SelectModeConfig.MULTIPLE)
                            .isDisplayCamera(true)
                            .setMaxSelectNum(BaseConfig.selectMaxImage)
                            .setSelectedData(data)
                    selectionModel.forResult(launcherResult)
                }

            })
        }
        mViewBind.rgType.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_1 -> {
                    mViewBind.lvYichang.visibility = View.GONE
                }

                R.id.rb_2 -> {
                    mViewBind.lvYichang.visibility = View.VISIBLE
                }
            }
        }
    }

    override fun createObserver() {
        mViewModel.run {
            problemTypes.observe(this@OrderAddKtActivity) { resultState ->
                parseState(resultState, {
                    problem_type.clear()
                    it.forEach { typeKt ->
                        if (typeKt.pid == "0") {
                            it.forEach { typeKt2 ->
                                if (typeKt.id == typeKt2.pid) {
                                    typeKt.problemType2.add(typeKt2)
                                }
                            }
                            problem_type.add(typeKt)
                        }
                    }

                    CircleDialog.Builder()
                        .setItems(problem_type) { view, position ->
                            if (problem_type[position].problemType2.size == 0) {
                                mViewBind.tvType.text = problem_type[position].itemLabel
                            } else {
                                CircleDialog.Builder()
                                    .setItems(problem_type[position].problemType2) { _, position2 ->
                                        mViewBind.tvType2.text =
                                            problem_type[position].itemLabel + "," + problem_type[position].problemType2[position2].itemLabel
                                        true
                                    }
                                    .setNegative("取消", null)
                                    .show(supportFragmentManager)
                            }
                            true
                        }
                        .setNegative("取消", null)
                        .show(supportFragmentManager)
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
            file.observe(this@OrderAddKtActivity) { resultState ->
                parseState(resultState, {
                    log_e("device:" + it.id)
                    imageIds = if(imageIds.isEmpty()){
                        it.id
                    }else{
                        imageIds+","+it.id
                    }
                    if (mData.isNotEmpty()) upFile()
                    else {
                        dismissLoading()
                        Toaster.show("上传成功")
                    }
                }, {
                    Toaster.show(it.errorMsg)
                })
            }
        }

    }

    private fun createActivityResultLauncher(): ActivityResultLauncher<Intent> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == RESULT_OK) {
                val selectList = PictureSelector.obtainSelectorList(result.data)
                analyticalSelectResults(selectList)
            } else if (resultCode == RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }

    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: java.util.ArrayList<LocalMedia>) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(mContext, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(mContext, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            //val file = File(media.compressPath)
        }
        val isMaxSize = result.size == imageAdapter.selectMax
        val oldSize: Int = imageAdapter.data.size
        imageAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
        imageAdapter.data.clear()
        imageAdapter.data.addAll(result)
        imageAdapter.notifyItemRangeInserted(0, result.size)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        destroyLocation()
    }

    override fun onBindViewClick() {
        setOnclickNoRepeat(
            mViewBind.lvTitle.ivLeft,
            mViewBind.lvTitle.tvRight,
            mViewBind.tvName,
            mViewBind.tvAddress,
            mViewBind.tvLaiyuan,
            mViewBind.btCancel,
            mViewBind.btOk,
            mViewBind.tvType2,
            mViewBind.tvType
        ) {
            when (it.id) {
                R.id.iv_left -> {
                    finish()
                }

                R.id.tv_name -> {
                   // mViewModel.getDeviceType("3")
                }

                R.id.tv_address -> {
                    initLocation()
                }

                R.id.tv_laiyuan -> {
                    CircleDialog.Builder()
                        .setItems(form_type) { _, position ->
                            mViewBind.tvLaiyuan.text = form_type[position].itemLabel
                            true
                        }
                        .setNegative("取消", null)
                        .show(supportFragmentManager)
                }

                R.id.tv_type2,
                R.id.tv_type -> {
                    mViewModel.getProblemType("0")
                }

                R.id.bt_cancel -> {
                    finish()
                }

                R.id.bt_ok -> {
                    mData.clear()
                    mData.addAll(imageAdapter.data)
                    imageIds=""
                    if (mData.isNotEmpty()) {
                        showLoading("正在上传图片")
                        upFile()
                    }else{
                        Toaster.show("请上传图片")
                    }
                }
            }
        }
    }

    private fun upFile() {
        var file = File(mData[0].compressPath)
        mViewModel.upFile(file)
        mData.removeAt(0)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(event: EventBusModel) {
        when (event.type) {
            EventBusConfig.FINISH -> {
            }

            else -> {}
        }
    }

    private fun initLocation() {
        locationClient = AMapLocationClient(this)
        locationOption = getDefaultOption()
        locationClient.setLocationOption(locationOption)
        locationClient.setLocationListener(this)
        startLocation()
    }

    private fun getDefaultOption(): AMapLocationClientOption {
        val mOption = AMapLocationClientOption()
        mOption.locationMode =
            AMapLocationClientOption.AMapLocationMode.Hight_Accuracy //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.isOnceLocation = true //可选，设置是否单次定位。默认是false
        mOption.isLocationCacheEnable = true //可选，设置是否使用缓存定位，默认为true
        return mOption
    }

    private fun startLocation() {
        showLoading("定位中")
        locationClient.setLocationOption(locationOption)
        locationClient.startLocation()
    }

    private fun stopLocation() {
        locationClient.stopLocation()
    }

    private fun destroyLocation() {
        if(::locationClient.isInitialized) {
            if (null != locationClient) {
                locationClient.onDestroy()
            }
        }
    }

    override fun onLocationChanged(location: AMapLocation?) {
        dismissLoading()
        if (null != location) {
            val sb = StringBuffer()
            if (location.errorCode == 0) {
                MmkvUtil.putString("lng", "" + location.longitude)
                MmkvUtil.putString("lat", "" + location.latitude)
                log_e("定位成功 lng=" + location.longitude + "  lat=" + location.latitude)
                log_e("address:" + location.toStr())
                if (location.address.isNotEmpty()) mViewBind.tvAddress.setText(location.address)
                val g = MapAppUtil.gcj02_To_Gps84(location.latitude, location.longitude)
                log_e("GPS==" + g[0] + "," + g[1])
            } else {
                log_e("定位失败错误码:${location.errorCode}\n")
                log_e("错误信息:${location.errorInfo}\n")
                log_e("错误描述:${location.locationDetail}\n")
            }
        } else {
            log_e("定位失败，loc is null")
        }
        stopLocation()
    }
}
